<?php

namespace app\store\controller;

use app\store\model\User as UserModel;
use app\store\model\user\Grade as GradeModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Env;
/**
 * 用户管理
 * Class User
 * @package app\store\controller
 */
class User extends Controller
{
    /**
     * 用户列表
     * @param string $nickName 昵称
     * @param int $gender 性别
     * @param int $grade 会员等级
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($nickName = '', $gender = null, $grade = null)
    {
        $model = new UserModel;
        $list = $model->getList($nickName, $gender, $grade);
        // 会员等级列表
        $gradeList = GradeModel::getUsableList();
        return $this->fetch('index', compact('list', 'gradeList'));
    }

    /**
     * 删除用户
     * @param $user_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->setDelete()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 用户充值
     * @param $user_id
     * @param int $source 充值类型
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function recharge($user_id, $source)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->recharge($this->store['user']['user_name'], $source, $this->postData('recharge'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 修改会员等级
     * @param $user_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function grade($user_id)
    {
        // 用户详情
        $model = UserModel::detail($user_id);
        if ($model->updateGrade($this->postData('grade'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 修改上级
     * @param $user_id
     * @return array|bool
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function relationship($user_id)
    {
        // 用户详情
        $relationship = $this->postData('relationship');
        $r_user_id = model('user')->where('phone','=',$relationship['phone'])->where('is_delete','=',0)->value('user_id');
        if(!$r_user_id){
            return $this->renderError('用户不存在');
        }
       // $model = UserModel::detail($user_id);
        //$model->updateGrade($this->postData('grade'))
        $res = model('user')->where('user_id','=',$user_id)->setField(['referee_id'=>$r_user_id]);
        if ($res !== false) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError( '操作失败');
    }
    public function import()
    {
        //ajax 文件跨域 验证
        $request_method = $_SERVER['REQUEST_METHOD'];
        if ($request_method === 'OPTIONS') {
            header('Access-Control-Allow-Origin:*');
            header('Access-Control-Allow-Credentials:true');
            header('Access-Control-Allow-Methods:GET, POST, OPTIONS');
            header('Access-Control-Max-Age:1728000');
            header('Content-Type:text/plain charset=UTF-8');
            header('Content-Length: 0',true);
            header('status: 204');
            header('HTTP/1.0 204 No Content');
        }

        $file = request()->file('file');
        if(!$file){
            return $this->renderError('请上传文件');
        }

        $info = $file->validate(['size'=>5*1024*1024,'ext'=>'xls,xlsx'])->move( './uploads');
        if(!$info){
            return $this->renderError('文件过大或格式不正确导致上传失败-_-!');
        }

        //获取上传到后台的文件名
        $fileName = $info->getSaveName();
        //获取文件路径
        //$filePath = $this->request->domain().DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$fileName;

        //判断文件类型
        $suffix = $info->getExtension();
        if($suffix=="xlsx"){
            $objReader = IOFactory::createReader('Xlsx');
        }else{
            $objReader = IOFactory::createReader('Xls');
        }
        $objPHPExcel = $objReader->load(Env::get('root_path').'uploads/'.$info->getSaveName());

        //读取默认工作表
        $worksheet = $objPHPExcel->getSheet(0);
        //取得一共有多少行
        $allRow = $worksheet->getHighestRow();

        for ($i = 2; $i <= $allRow; $i++) {
            $data = [];
            //$goods_code = GoodsCodeModel::getGoodsCodeNo();
            $phone = $objPHPExcel->getActiveSheet()->getCell('A'.$i)->getValue();
            $user = UserModel::where('phone',$phone)->find();
            if(empty($user)){
                $data['phone'] = $phone;
                $data['nickName'] = $objPHPExcel->getActiveSheet()->getCell('B'.$i)->getValue();
                $data['referee_phone'] = $objPHPExcel->getActiveSheet()->getCell('E'.$i)->getValue();
                $data['grouping'] = $objPHPExcel->getActiveSheet()->getCell('F'.$i)->getValue();
                $data['team'] = $objPHPExcel->getActiveSheet()->getCell('G'.$i)->getValue();
                $data['customer_num'] = $objPHPExcel->getActiveSheet()->getCell('J'.$i)->getValue();
                $data['balance'] = $objPHPExcel->getActiveSheet()->getCell('L'.$i)->getValue();
                $data['expend_money'] = $objPHPExcel->getActiveSheet()->getCell('N'.$i)->getValue();
                $data['pay_money'] = $objPHPExcel->getActiveSheet()->getCell('M'.$i)->getValue();
                $data['extension'] = $objPHPExcel->getActiveSheet()->getCell('P'.$i)->getValue();
                $data['code'] = $objPHPExcel->getActiveSheet()->getCell('H'.$i)->getValue();
                $data['grade_id'] = 1;
                $data['wxapp_id'] = 10001;
                $data['create_time'] = time();
                //       var_dump($data);die;
                UserModel::create($data);
            }

//            //防止出现空白Excel导致mysql报错，对数据做下判断
//            if(empty($data['order_sn_third']) && empty($data['goods_sn'])){
//                //跳出循环
//                break;
//            }
        }

        return $this->renderSuccess('导入完成', url('goods.code/index'));
    }
}
